#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# Openfuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

#!/bin/bash

# 脚本用途：自动调用 deploy_temp_task.py 部署三次
# 第一次参数：-n occupie-cpu-task-1 -req 31 -limit 31
# 第二次参数：-n occupie-cpu-task-2 -req 31 -limit 31
# 第三次参数：-n occupie-cpu-task-2 -req 4 -limit 4
# 第四次参数：-n occupie-cpu-task-2 -req 32 -limit 32
# 删除第三次部署

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_SH_FILE="${SCRIPT_DIR}/deploy_temp_task.py"

# 检查部署脚本是否存在
if [[ ! -f "${DEPLOY_SH_FILE}" ]]; then
    echo "错误：未找到部署脚本 deploy_temp_task.py"
    exit 1
elif [[ ! -x "${DEPLOY_SH_FILE}" ]]; then
    chmod +x "${DEPLOY_SH_FILE}"
fi

echo "开始执行 numa-distance-close-pre.sh 部署任务..."

echo "------------------------"
echo "部署第一次：occupie-cpu-task-1"
python3 "${DEPLOY_SH_FILE}" -n "occupie-cpu-task-1" -r 31 -l 31

if [[ $? -ne 0 ]]; then
    echo "第一次部署失败，终止脚本"
    exit 1
fi

echo "------------------------"
echo "部署第二次：occupie-cpu-task-2"
python3 "${DEPLOY_SH_FILE}" -n "occupie-cpu-task-2" -r 31 -l 31

if [[ $? -ne 0 ]]; then
    echo "第二次部署失败，终止脚本"
    exit 1
fi

echo "------------------------"
echo "部署第三次：occupie-cpu-task-3"
python3 "${DEPLOY_SH_FILE}" -n "occupie-cpu-task-3" -r 4 -l 4

if [[ $? -ne 0 ]]; then
    echo "第三次部署失败，终止脚本"
    exit 1
fi

echo "------------------------"
echo "部署第四次：occupie-cpu-task-4"
python3 "${DEPLOY_SH_FILE}" -n "occupie-cpu-task-4" -r 32 -l 32

if [[ $? -ne 0 ]]; then
    echo "第四次部署失败，终止脚本"
    exit 1
fi

echo "------------------------"
echo "删除第三次部署：occupie-cpu-task-3"
# 删除资源
kubectl delete deployment occupie-cpu-task-3

if [[ $? -ne 0 ]]; then
    echo "删除第三次部署失败，终止脚本"
    exit 1
fi

# 删除验证
# ------------------------
echo "------------------------"
echo "等待 occupie-cpu-task-3 被彻底删除..."
kubectl wait deployment/occupie-cpu-task-3 --for=delete --timeout=60s -n default

if [[ $? -eq 0 ]]; then
    echo "occupie-cpu-task-3 已成功删除"
else
    echo "错误：删除 occupie-cpu-task-3 超时或失败"
    exit 1
fi

# 等待前删除的deployment释放其所绑定的cpu核
sleep 10

echo "------------------------"
echo "numa-distance-close-pre.sh 执行完成"